package com.honghu.cloud.utils;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;

/**
 * 系统工具类，用来快速处理,系统默认将该工具类添加到ModelAndView中，前台可以使用$!CommUtil.xxx调用该工具类
 * @author Administrator
 *
 */
public class CommUtil {
	
	public static String getURL(HttpServletRequest request) {
		String contextPath = request.getContextPath().equals("/") ? ""
				: request.getContextPath();
		String url = "http://" + request.getServerName();
		if (null2Int(Integer.valueOf(request.getServerPort())) != 80) {
			url = url + ":"
					+ null2Int(Integer.valueOf(request.getServerPort()))
					+ contextPath;
		} else {
			url = url + contextPath;
		}
		return url;
	}
	
	public static int null2Int(Object s) {
		int v = 0;
		if (s != null) {
			try {
				v = Integer.parseInt(s.toString());
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	public static String null2String(Object s) {
		return s == null ? "" : s.toString().trim();
	}
	
	public static Long null2Long(Object s) {
		Long v = Long.valueOf(-1L);
		if (s != null) {
			try {
				v = Long.valueOf(Long.parseLong(s.toString()));
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	/**
	 * 计算当前域名，不含www的顶级域名
	 * 
	 * @param request
	 * @return
	 */
	public static String generic_domain(HttpServletRequest request) {
		String system_domain = "localhost";
		String serverName = request.getServerName();
		if (isIp(serverName)) {
			system_domain = serverName;
		} else if (serverName.indexOf(".") == serverName.lastIndexOf(".")) {
			system_domain = serverName;
		} else {
			system_domain = serverName.substring(serverName.indexOf(".") + 1);
		}
		return system_domain;
	}
	
	/**
	 * 判断是否是一个IP
	 * 
	 * @param IP
	 * @return
	 */
	public static boolean isIp(String IP) {
		boolean b = false;
		IP = trimSpaces(IP);
		if (IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
			String[] s = IP.split("\\.");
			if ((Integer.parseInt(s[0]) < 255)
					&& (Integer.parseInt(s[1]) < 255)
					&& (Integer.parseInt(s[2]) < 255)
					&& (Integer.parseInt(s[3]) < 255)) {
				b = true;
			}
		}
		return b;
	}
	
	/**
	 * 去掉IP字符串前后所有的空格
	 * 
	 * @param IP
	 * @return
	 */
	public static String trimSpaces(String IP) {
		while (IP.startsWith(" ")) {
			IP = IP.substring(1, IP.length()).trim();
		}
		while (IP.endsWith(" ")) {
			IP = IP.substring(0, IP.length() - 1).trim();
		}
		return IP;
	}
	
	/**
	 * 读取图片为bufferedimage,修正图片读取ICC信息丢失而导致出现红色遮罩
	 * 
	 * @param image
	 * @return
	 */
	public static BufferedImage toBufferedImage(Image image) {
		if ((image instanceof BufferedImage)) {
			return (BufferedImage) image;
		}
		image = new ImageIcon(image).getImage();

		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		try {
			int transparency = 1;

			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null),
					image.getHeight(null), transparency);
		} catch (HeadlessException localHeadlessException) {
		}
		if (bimage == null) {
			int type = 1;

			bimage = new BufferedImage(image.getWidth(null),
					image.getHeight(null), type);
		}
		Graphics g = bimage.createGraphics();

		g.drawImage(image, 0, 0, null);
		g.dispose();

		return bimage;
	}

	public static double null2Double(Object s) {
		double v = 0.0D;
		if (s != null) {
			try {
				v = Double.parseDouble(null2String(s));
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	public static float null2Float(Object s) {
		float v = 0.0F;
		if (s != null) {
			try {
				v = Float.parseFloat(s.toString());
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	/**
	 * 浮点数乘法
	 * @param a
	 * @param b
	 * @return
	 */
	public static double mul(Object a, Object b) {
		BigDecimal e = new BigDecimal(null2Double(a));
		BigDecimal f = new BigDecimal(null2Double(b));
		double ret = e.multiply(f).doubleValue();
		DecimalFormat df = new DecimalFormat("0.00");
		return Double.valueOf(df.format(ret)).doubleValue();
	}
	
	public static boolean createFolder(String folderPath) {
		boolean ret = true;
		try {
			File myFilePath = new File(folderPath);
			if ((!myFilePath.exists()) && (!myFilePath.isDirectory())) {
				ret = myFilePath.mkdirs();
			}
		} catch (Exception e) {
			ret = false;
		}
		return ret;
	}
	
	
	/**
	 * 
	 * @param currentPage
	 * @param orderBy
	 * @param orderType
	 * @return
	 */
	public  static Map<String, Object> getParams(String currentPage, Integer pageSize,
			String orderBy, String orderType) {
		int cp = CommUtil.null2Int(currentPage);

		Map<String, Object> params = Maps.newHashMap();
		// 这个src_currentPage需要返回到前台,让前台显示页码用的

		if (cp == 0) {
			cp = 1;
		}

		if (pageSize == null) {
			pageSize = 12;
		}

		params.put("currentPage", cp);
		params.put("pageSize", pageSize);

		params.put("orderBy", orderBy);
		params.put("orderType", orderType);

		if (StringUtils.isBlank(orderBy) || StringUtils.isBlank(orderType)) {
			params.put("orderBy", "addTime");
			params.put("orderType", "asc");
		}

		return params;
	}
}
